package com.cjm.one.security.fillter;

import com.cjm.one.common.constant.RedisConstants;
import com.cjm.one.common.result.Result;
import com.cjm.one.common.result.ResultCodeEnum;
import com.cjm.one.common.utils.AuthSysUserContextHolder;
import com.cjm.one.common.utils.AuthCustomerContextHolder;
import com.cjm.one.common.utils.JSONUtils;
import com.cjm.one.common.utils.ResponseUtil;
import com.cjm.one.model.custom.entity.CustomerInfo;
import com.cjm.one.model.system.entity.SysUserInfo;
import com.cjm.one.security.config.PermissionPathPropertis;
import com.fasterxml.jackson.core.JsonProcessingException;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
public class AppTokenAuthenticationFilter extends OncePerRequestFilter {
    private RedisTemplate redisTemplate;

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    private  PermissionPathPropertis permissionPathPropertis ;

    public AppTokenAuthenticationFilter(RedisTemplate redisTemplate, PermissionPathPropertis permissionPathPropertis) {
        this.redisTemplate = redisTemplate;
        this.permissionPathPropertis = permissionPathPropertis;

    }
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        String uri = request.getRequestURI();
        log.info("app请求的路径uri:" + uri);
        log.info("请求方式：{}", request.getMethod());
        log.info("Query参数：{}", request.getQueryString());
//        log.info("Body参数：{}",request.getReader().lines().collect(Collectors.joining(System.lineSeparator())));
        for (String url : permissionPathPropertis.getIgnoreUrlList()) {
            if (antPathMatcher.match(url, uri)) {
                log.info("放行:" + uri);
                chain.doFilter(request, response);
                return;
            }
        }
        String token = request.getHeader("authorization");
        log.info("token:" + token);
        if (StringUtils.hasText(token)) {
            String cleanToken = token.replaceFirst("(?i)^Bearer\\s+", "").trim();
            String str = (String) redisTemplate.opsForValue().get(RedisConstants.APP_USER_LOGIN_KEY_TOKEN + cleanToken);
            log.info("str1:" + str);
            if (!StringUtils.hasText(str)) {
                ResponseUtil.out(response, Result.build(null, ResultCodeEnum.LOGIN_AUTH));
            }
            log.info("str:" + str);
            CustomerInfo customerInfo = JSONUtils.toBean(str, CustomerInfo.class);
            log.info("customerInfo:" + customerInfo);
            AuthCustomerContextHolder.setAuthContextCustomer(customerInfo);
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(customerInfo.getEmail(), null, new ArrayList<>());
            SecurityContextHolder.getContext().setAuthentication(authentication);
            chain.doFilter(request, response);

        }
    }
}
